import axios from 'axios';
import { BaseUrl } from './const';

// axios实例
const httpService = axios.create({
  baseURL: BaseUrl(),
  timeout: 3000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

// 请求拦截器
httpService.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
httpService.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * GET请求
 * @param url
 * @param params
 * @returns
 */
export function get(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    httpService
      .get(url, { params })
      .then((res) => resolve(res.data))
      .catch((err) => reject(err));
  });
}

/**
 * POST请求
 * @param url
 * @param data
 * @param params
 * @returns
 */
export function post(url: string, data = {}, params = {}) {
  return new Promise((resolve, reject) => {
    httpService
      .post(url, { params, data })
      .then((res) => resolve(res.data))
      .catch((err) => reject(err));
  });
}

/**
 * 网络请求
 * @param url
 * @param method
 * @param options
 * 支持简单对象或URLSearchParams对象
 * params: {} url参数
 * data: {} 请求体
 */
type ReqOptions = {
  params?: Object;
  data?: Object;
};
export function request(url: string, method: string, options: ReqOptions = {}) {
  return new Promise((resolve, reject) => {
    httpService({
      url: url,
      method: method,
      params: options.params,
      data: options.data
    })
      .then((res) => resolve(res.data))
      .catch((err) => reject(err));
  });
}
